﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SetSailProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            setup = ExistsUpdate();
        }

        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        public bool setup { get; set; }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string path = System.Environment.CurrentDirectory;
                if (setup)
                {
                    DialogResult dr = MessageBox.Show("检测到软件有更新，是否立即更新？", "提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.OK)
                    {

                        //替换文件
                        DirectoryInfo root = new DirectoryInfo(path + "\\SetSailUpdate");
                        foreach (FileInfo f in root.GetFiles())
                        {
                            if (File.Exists(path + "\\" + f.Name))
                            {
                                f.Attributes = FileAttributes.Normal;
                                //File.Delete(path + "\\" + f.Name);
                                File.Copy(path + "\\SetSailUpdate\\" + f.Name, path + "\\" + f.Name, true);
                            }
                        }
                        Application.Exit();
                        ProcessStartInfo psi = new ProcessStartInfo();

                        psi.FileName = AppDomain.CurrentDomain.BaseDirectory + "SetSailReadFileTools.exe";
                        psi.UseShellExecute = false;
                        psi.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
                        psi.CreateNoWindow = true;
                        Process.Start(psi);
                    }
                    else
                    {
                        Application.Exit();
                        Process[] processList = Process.GetProcessesByName("SetSailReadFileTools");
                        if (processList != null && processList.Length > 0)
                            processList[0].Kill();
                    }
                }
                else
                {
                    Application.Exit();
                    ProcessStartInfo psi = new ProcessStartInfo();

                    psi.FileName = AppDomain.CurrentDomain.BaseDirectory + "SetSailReadFileTools.exe";
                    //psi.UseShellExecute = false;
                    psi.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    //psi.CreateNoWindow = true;
                    Process.Start(psi);
                    string path2 = Application.StartupPath + "\\SetSailUpdate";
                    if (Directory.Exists(path2))
                    {
                        string[] file = Directory.GetFileSystemEntries(path2);
                        foreach (var item in file)
                        {
                            if (File.Exists(item))
                            {
                                File.Delete(item);
                            }
                        }
                        if (Directory.Exists(path2))
                            Directory.Delete(path2);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 检测软件是否需要升级
        /// </summary>
        private static bool ExistsUpdate()
        {
            bool flag = false;
            try
            {
                string path = System.Environment.CurrentDirectory;
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(path + "\\SetSailReadFileTools.exe");
                string version = fvi.FileVersion;
                string[] verNum = version.Split('.');
                string verNew = (Convert.ToInt32(version.Replace(".", "")) + 1).ToString();
                string[] arr = Common.FTPGetFileList("ftp://146.56.250.94", "ftp_setsailUpdate", "@synca123.");
                foreach (var item in arr)
                {
                    if (item.Replace(".", "").Trim() == verNew.Trim())
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    string[] arrFile = Common.FTPGetFileList("ftp://146.56.250.94" + "/" + verNew, "ftp_setsailUpdate", "@synca123.");
                    string UpdatePath = "SetSailUpdate";
                    if (!Directory.Exists("SetSailUpdate"))
                    {
                        Directory.CreateDirectory(path + "\\" + UpdatePath);
                    }
                    //下载文件
                    foreach (var item in arrFile)
                    {
                        string str = Common.FTPDownloadFile("ftp://146.56.250.94/" + item, "ftp_setsailUpdate", "@synca123.", path + "\\" + UpdatePath, item.Split('/')[1]);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return flag;
        }
    }
}
